package com.dongjiantong.common.model;

import com.dongjiantong.common.exceptions.HttpCode;
import com.google.common.base.MoreObjects;

import java.io.Serializable;

/**
 * 包装返回信息
 * Created by cao on 2017/10/27.
 */
public class Response<T> implements Serializable {
    private static final long serialVersionUID = -750644833749014618L;
    private boolean success;
    private Integer code;
    private T result;
    private String message;

    public Response() {
    }

    public boolean isSuccess() {
        return this.success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public Integer getCode() {
        return this.code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public T getResult() {
        return this.result;
    }

    public void setResult(T result) {
        this.success = true;
        this.result = result;
    }

    public String getMessage() {
        return this.message;
    }

    public void setMessage(String message) {
        this.success = false;
        this.message = message;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("success", this.success)
                .add("code", this.code)
                .add("result", this.result)
                .add("message", this.message)
                .omitNullValues().toString();
    }

    public static <T> Response<T> ok(T data) {
        Response<T> resp = new Response();
        resp.setCode(HttpCode.OK.getCode());  //200
        resp.setResult(data);
        return resp;
    }


    public static <T> Response<T> ok() {
        return ok(null);
    }

    public static <T> Response<T> fail(String error) {
        Response<T> resp = new Response();
        resp.setMessage(error);
        resp.setCode(HttpCode.INTERNAL_SERVER_ERROR.getCode()); //500
        return resp;
    }

    public static <T> Response<T> fail(HttpCode code,String error) {
        Response<T> resp = new Response();
        resp.setMessage(error);
        resp.setCode(code.getCode());
        return resp;
    }
    public static <T> Response<T> fail(Integer code,String error) {
        Response<T> resp = new Response();
        resp.setMessage(error);
        resp.setCode(code);
        return resp;
    }
}